package com.redlight.pool;

import com.redlight.base.Global;
import com.sun.javafx.collections.MappingChange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by chao on 2019/1/23.
 */
@Component
public class ThreadPoolFactory {
    private Map<String,ThreadPool> pools=null;
    private Logger logger= LoggerFactory.getLogger(getClass());
    @Resource
    private ThreadPoolInit threadPoolInit;
    private static volatile ThreadPoolFactory threadPoolFactory;
    public ThreadPoolFactory(){
    }
    public static ThreadPoolFactory getInstance() {
        if (threadPoolFactory == null) {
            synchronized (ThreadPoolFactory.class) {
                if (threadPoolFactory == null) {
                    threadPoolFactory = new ThreadPoolFactory();
                }
            }
        }
        return threadPoolFactory;
    }


    /**
     * 初始化
     */
    @PostConstruct
    public void init(){
        logger.info("开始初始化线程池工厂。。。。");
        try{
            Thread.sleep(1000);
            if(threadPoolInit.getPoolArgMap()!=null){
                pools=new HashMap<String,ThreadPool>();
                Set<String> poolIds=threadPoolInit.getPoolArgMap().keySet();
                for(String poolId :poolIds){
                    newPool(threadPoolInit.getPoolArgMap().get(poolId));
                }
            }
        }catch (Exception e){
            logger.error("初始化线程池失败");
        }
    }

    /**
     * 创建一个线程池
     * @param args
     * @return
     */
    public synchronized ThreadPool newPool(PoolArgs args) throws Exception{
        if(pools==null){
            return null;
        }
        if(pools.containsKey(args.getId()))
            return pools.get(args.getId());
        ThreadPool pool=new ThreadPool();
        pool.init(args);
        pools.put(args.getId(),pool);
        return pool;
    }

    /**
     *
     * 获取线程池
     * @param id
     * @return
     */
    public ThreadPool getPool(String id){
        if(pools!=null)
            return pools.get(id);
        return null;
    }
    public void stopAllPools(){
        if(pools!=null &&pools.size()>0){
            Set<String> keys=pools.keySet();
            for(String key :keys){
                pools.get(key).stop();
            }
        }
        pools=null;
    }


}
